package com.dfrz.problem.utils;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;

public abstract class SessionFactoryUtil {
	protected  static SessionFactory  factory = null;
	
	static{
		Configuration cfg = new Configuration().configure();
		StandardServiceRegistry registrty = new StandardServiceRegistryBuilder()
			.applySettings(cfg.getProperties()).build();
		factory = cfg.buildSessionFactory(registrty);
		
	}
	
	private final static ThreadLocal<Session> threadSession = new ThreadLocal<Session>();
	
	public static Session getSession(){
		//判断当前线程中是否已经有session了
		Session session = threadSession.get();
		if(session==null){
			session = factory.openSession();
			threadSession.set(session);
		}
		return session;
	}
	
	public static void beginTransaction(){
		getSession().beginTransaction();
	}
	
	public static void commit(){
		getSession().getTransaction().commit();
	}
	public static void rollback(){
		getSession().getTransaction().rollback();
	}
	
	public static void clear(){
		getSession().clear();
		getSession().close();
		threadSession.remove();
	}
	
	public static void close(){
		factory.close();
	}
	
}
